package cn.tedu._03vehicle.base.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUESTS_PER_SER_MINUTE = 3;// 每分钟最多请求次数
    private static final int WINDOW_SIZE_SECONDS = 60;//时间窗口

    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();

    private final ConcurrentHashMap<String, LocalDateTime> lastResetTimes = new ConcurrentHashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取客户端IP地址
        String clientId = request.getRemoteAddr();
        //2.获取该IP地址最后的重置时间
        LocalDateTime lastResetTime = lastResetTimes.get(clientId);
        //3.判断
        if(lastResetTime==null || lastResetTime.now().isAfter(lastResetTime.plusSeconds(WINDOW_SIZE_SECONDS))){
            clientCounts.put(clientId,0);//重置计数器
            lastResetTimes.put(clientId,LocalDateTime.now());
        }
        //4.访问次数+1
        Integer count = clientCounts.merge(clientId,1,Integer::sum);
        //5.判断次数
        if (count>MAX_REQUESTS_PER_SER_MINUTE){
            throw new RuntimeException("访问次数超出限制");
        }
        return true;
    }
}
